﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using MvcEngine.Core.Repositories;

using MvcEngine.Core;
using MvcEngine.Core.Content;
using MvcEngine.Core.Pagination;
using MvcEngine.Core.Base;
using MvcEngine.Core.Extensions;

namespace MvcEngine.LinqToSqlProvider
{
    public class PageRepository : Repository, IPageRepository
    {
        public Page Get(string pageName, Guid siteId)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Pages().SingleOrDefault(p => p.Name == pageName && p.SiteId == siteId);
            }
        }

        public Page Get(Guid pageId)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Pages().SingleOrDefault(p => p.Id == pageId);
            }
        }

        public IPagination<Page> GetAll(Guid siteId, int pageIndex, int count)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.GetTable<Page>().Where(t => ((IUnique)t).SiteId == siteId).OrderBy(p => p.OrderNumber).GetPage(pageIndex, count);
            }
        }

        public IList<Page> GetAll(bool onlyVisible, Guid siteId)
        {
            using (var contextManager = CreateContextManager(true))
            {
                if (onlyVisible)
                    return contextManager.Context.GetTable<Page>().Where(t => t.Visible == onlyVisible && ((IUnique)t).SiteId == siteId).OrderBy(p => p.OrderNumber).ToList();
                return contextManager.Context.GetTable<Page>().Where(t => ((IUnique)t).SiteId == siteId).OrderBy(p => p.OrderNumber).ToList();
            }
        }

        public void Add(Page entity)
        {
            using (var contextManager = CreateContextManager(false))
            {
                contextManager.Context.Pages().InsertOnSubmit(entity);
                contextManager.Commit();
            }
        }

        public void Update(Page entity)
        {
            using (var contextManager = CreateContextManager(false))
            {
                contextManager.Commit();
            }
        }

        public void Delete(Guid pageId)
        {
            using (var contextManager = CreateContextManager(false))
            {
                var page = contextManager.Context.Pages().SingleOrDefault(l => l.Id == pageId);
                if (page != null)
                {
                    contextManager.Context.Pages().DeleteOnSubmit(page);
                    contextManager.Commit();
                }
            }
        }

        public void DeleteAll(Guid siteId)
        {
            throw new NotImplementedException();
        }
    }
}
